package cn.zongtilei;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class LastAccessTimeServlet
 */
public class LastAccessTimeServlet extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1。记录当前访问时间，设置到cookie上
		Date date = new Date();
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // 将时间转换为几几年几月几日的类型
		String shijian = simpleDateFormat.format(date); // 把Date型的字符串转换成特定格式的String类型
		Cookie cookie = new Cookie("lastAccessTime", shijian); // 将cookie实例化
		resp.addCookie(cookie);

		// 2.获得cookie的值显示页面
		String lastAccessTime = null;
		Cookie[] cookies = req.getCookies(); // 返回的是所有Cookie对象
		if (cookie != null) {
			for (Cookie cookie2 : cookies) {
				if (cookie2.getName().equals("lastAccessTime")) {
					lastAccessTime = cookie2.getValue();
				}
			}

		}
		// 在页面显示
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		if (lastAccessTime == null) {
			writer.println("这是您第一次访问");

		} else {
			writer.println("您上次访问时间" + lastAccessTime);
		}
	}

}
